using NUnit.Framework;
using ValidationFramework;
using ValidationFramework.Reflection;

namespace ExampleLibraryCSharp
{
    [TestFixture]
    public class AddCustomRuleWithTypeCacheExample
    {

        #region Example

        public class Person
        {

            public string Name
            {
                get;
                set;
            }



            public static void CheckIsNotEmpty(object sender, CustomValidationEventArgs e)
            {
                var name = (string)e.TargetMemberValue;
                if (string.IsNullOrEmpty(name))
                {
                    e.IsValid = false;
                }
                else
                {
                    e.IsValid = true;
                }
            }

        }
            [TestFixture]
            public class ExampleUsage
            {
                [Test]
                public void Run()
                {

                    var person = new Person();
                    var personTypeHandle = typeof (Person).TypeHandle;
                    var typeDescriptor = TypeCache.GetType(personTypeHandle);
                    var propertyDescriptor =
                        typeDescriptor.GetOrCreatePropertyDescriptor("Name");
                    var rule = new CustomRule(Person.CheckIsNotEmpty, "Name cannot be empty.");
                    propertyDescriptor.Rules.Add(rule);

                    var validationManager = ValidationManagerFactory.GetPropertyValidationManager(person);
                    validationManager.Validate("Name");
                    Assert.IsFalse(validationManager.IsValid);

                    person.Name = "John";

                    validationManager = ValidationManagerFactory.GetPropertyValidationManager(person);
                    validationManager.Validate("Name");
                    Assert.IsTrue(validationManager.IsValid);
                }
            }
        #endregion
    }
}